package com.marion.mrpc.codec;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 基于Jackson的JSON序列化
 *
 * @author marion
 * @date 2021/9/4
 */
public class JSONEncoder implements Encoder {

    private ObjectMapper objectMapper;

    public JSONEncoder() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        this.objectMapper = objectMapper;
    }

    public JSONEncoder(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public byte[] encode(Object value) throws EncodeExpception {
        try {
            return this.objectMapper.writeValueAsBytes(value);
        } catch (Exception e) {
            throw new EncodeExpception();
        }
    }

    @Override
    public String encodeAsString(Object value) throws EncodeExpception {
        try {
            return this.objectMapper.writeValueAsString(value);
        } catch (Exception e) {
            throw new EncodeExpception();
        }
    }
}
